from py2neo import Graph,Node,Relationship,NodeMatcher,RelationshipMatcher
from app.neo4jHelper.helper import connect,getPropertyOnNode,selectNodeByID

relationDict = {'中药组方':["方剂组成"],"中药材":["药材组分","药材来源植物名"],"化合物":["化合物对应靶点"],"靶点":["化合物对应靶点","靶点对应疾病"],"疾病":["靶点对应疾病"],"来源植物名":["药材来源植物名"]}

categoryDict = {'方剂组成':['中药组方','中药材'],'药材组分':['中药材','化合物'],'药材来源植物名':['中药材','来源植物名'],'化合物对应靶点':['化合物','靶点'],'靶点对应疾病':['靶点','疾病']}

def getNodeRelation(nodeID,selectType):
    """
    根据结点和结点类型获取需要的关系，不同的结点类型用不同的关系
    """
    global relationDict 
    print('nodeID',nodeID)
    print('selectType',selectType)
    try:
        node = selectNodeByID(nodeID,selectType)
    except:
        print("结点未找到！")
    relations = relationDict.get(selectType,[])

    if selectType == '疾病' or selectType == '来源植物名':
        direction = 1
    else:
        direction = 0 
    return node, relations,direction

def selectNodeByRelation(node,relation,direction=0):
    """
    根据关系查找和结点node相连的所有结点
    """
    print(node,relation)
    graph = connect()
    rel_matcher = RelationshipMatcher(graph)
    print('dire',direction)
    # 查找节点A的所有R关系
    if direction == 0:
        rels = rel_matcher.match((node,), r_type=relation)
    else:
        rels = rel_matcher.match((None,node), r_type=relation)
    print(rels.count())

    # 遍历所有R关系，获取关系的另一个节点
    nodes = []
    for rel in rels:
        if rel.start_node == node:
            nodes.append(rel.end_node)  
        elif rel.end_node == node:
            nodes.append(rel.start_node)
    return nodes

def getRelationNodeList(nodes):
    """
    只返回关系结点的name和id属性
    """
    result = []
    for node in nodes:
        temp = {}
        if '中文名' in node.keys():
            temp['name'] = getPropertyOnNode(node)['中文名']
        else:
            temp['name'] = getPropertyOnNode(node)['name']
        if 'ID' in node.keys():
            temp['id'] = getPropertyOnNode(node)['ID']
        else: 
            temp['id'] = getPropertyOnNode(node)['id']
        result.append(temp)
    return result

def getLabelOnNodes(nodes):
    if nodes:
        node = nodes[0]
        if node:
            labels = node.labels
            return str(labels).strip(':')
        else:
            return None

def getCategoriesByRelation(relations):

    categories = []
    global categoryDict
    for rel in relations:
        if rel in categoryDict.keys():
            categories += categoryDict[rel]
    categories = list(set(categories))
    return categories

def relationNodeTransfer(nodeID,selectType):
    """
    返回关系节点
    """
    result = []
    categories = []
    print('nodeID',nodeID)
    print('selectType',selectType)
    node,relations, direction = getNodeRelation(nodeID,selectType)
    print('direction:\n',direction)
    print('len(relations)\n',len(relations))
    if relations:
        if len(relations)>1:
            for rel in relations:
                temp = {}
                if rel == '化合物对应靶点':
                    direction = 1
                else:
                    direction = 0
                nodes = selectNodeByRelation(node,rel,direction)
                temp['nodesList'] = getRelationNodeList(nodes)
                temp['relation'] = rel
                category = getLabelOnNodes(nodes)
                # print('category',category)
                if category:
                    temp['category'] = category
                    categories.append(category)
                else:
                    temp['category'] = ''
                result.append(temp)
        else:
            temp = {}
            nodes = selectNodeByRelation(node,relations[0],direction)
            temp['nodesList'] = getRelationNodeList(nodes)
            temp['relation'] = relations[0]
            category = getLabelOnNodes(nodes)
            if category:
                temp['category'] = category
            else:
                temp['category'] = ''
            result.append(temp)
        categories = getCategoriesByRelation(relations)
        # print('categories',categories)
        return result,categories
    else:
        return None


        